<?php


namespace App\Http\observer;


use App\Exceptions\ApiException;
use App\Models\StarLog;
use App\Models\House as HouseModel;
use App\Models\Sys as SysModel;
use Illuminate\Support\Facades\Cache;
use App\Models\Chicken as ChickenModel;

class StarLogObserver
{
    public function creating(StarLog $starLog)
    {
        $house=HouseModel::where('id',$starLog->house_id)->first();
        if (!$house)
            throw new ApiException("项目不存在");
    }

    public function created(StarLog $starLog)
    {
        Cache::lock("count_star_".$starLog->invite_uid)->get(function ()use($starLog){
            $star_get_chicken=SysModel::getValue("star_get_chicken");
            $count=StarLog::where(["house_id"=>$starLog->house_id,"invite_uid"=>$starLog->invite_uid])->count();
            $chicken=ChickenModel::where("uid",$starLog->invite_uid)->first();
            if ($count>=$star_get_chicken&&!$chicken){
                $create=[
                    "uid"=>$starLog->invite_uid,
                    "grade"=>0,
                    "experience"=>0,
                    "food"=>0,
                    "rank"=>0,
                    "consume_food"=>0,
                    "hunger"=>0,
                    "limit"=>SysModel::getValue("feed_time")
                ];
                $res=ChickenModel::create($create);
            }
        });
    }
}
